﻿using NetMongo.Entity;
using NetMongo.Helper;
using NetMongo.Service;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;

namespace NetMongo.Controllers
{
    public class HomeController:Controller
    {
        //用户服务
        private static UserServices userService = new UserServices();        
        public ActionResult Index(string search = "")
        {
            Expression<Func<User, bool>> exp = a => a.Age > -1;
            if(!string.IsNullOrWhiteSpace(search))
            {
                exp = a => a.UserName.Contains(search);
            }
            List<User> list = userService.FindAll(exp);
            return View(list);
        }

        [HttpGet]
        public ActionResult UserAdd()
        {
            User model = new User();
            return View(model);
        }
        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="fc"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UserAdd(FormCollection fc,User model)
        {
            if(model != null)
            {
                model.CreateTime = DateTime.Now;
                if (userService.Add(model))
                {
                    return Json(new { success = true, msg = "新增成功" });
                }         
            }
            return Json(new { success = false, msg = "新增失败" });
        }
        
        [HttpGet]
        public ActionResult UserEdit(string id)
        {
            User model = userService.Get(id);
            if (model == null) model = new User();
            return View(model);
        }
        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="fc"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UserEdit(FormCollection fc,User model)
        {
            if(model != null)
            {
                userService.Update(model);
                return Json(new { success = true, msg = "编辑成功" });
            }
            return Json(new { success = false, msg = "编辑失败" });
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UserDelete(string id)
        {
            if(userService.Delete(id))
            {
                return Json(new { success = true, msg = "删除成功" });
            }
            return Json(new { success = false, msg = "删除失败" });
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}